package lrl.core.permission.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import lrl.core.permission.PermissionCheck;
import lrl.nsfw.role.entity.Role;
import lrl.nsfw.role.entity.RolePrivilege;
import lrl.nsfw.user.entity.User;
import lrl.nsfw.user.entity.UserRole;
import lrl.nsfw.user.service.UserService;

public class PermissionCheckImpl implements PermissionCheck {

	@Resource
	private UserService userService;
	
	@Override
	public boolean isAccessible(User user, String code) {
		
		List<UserRole> list = user.getUserRoles();
		if (list == null) {
			list = userService.getUserRolesByUserId(user.getId());
		}
		
		if (list != null && list.size() > 0) {
			for (UserRole userRole : list) {
				Role role = userRole.getId().getRole();
				Set<RolePrivilege> rolePrivileges = role.getRolePrivileges();
				for (RolePrivilege rolePrivilege : rolePrivileges) {
					if (code.equals(rolePrivilege.getId().getCode())) {
						return true;
					}
				}
			}
		}

		return false;
	}

}
